package com.leetcode.offer.chapter2;

import com.leetcode.basic.ListNode;

import java.util.Stack;

/**
 * @author Dennis Li
 * @date 2020/7/11 18:48
 */
public class ReversePrint_06 {

    int i = 0;
    // 标准 -- 基于反转链表
    // 1. 两种方法 -- 基于栈 -- 反转链表
    public int[] reversePrint(ListNode head) {
        ListNode node = reverse(head);
        int[] ints = new int[i];
        int j = 0;
        while(node != null){
            ints[j++] = node.val;
            node = node.next;
        }
        return ints;
    }

    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        while(head != null){
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
            i++;
        }
        return pre;
    }

    // 基于栈
    public int[] reversePrint2(ListNode head){
        Stack<Integer> stack = new Stack<>();
        int size = 0;
        while(head != null){
            stack.push(head.val);
            head = head.next;
            size++;
        }
        int[] ints = new int[size];

        for (int j = 0; j < size; j++) {
            ints[j] = stack.pop();
        }
        return ints;
    }

}
